/** 
 * @Description: 文件描述
 * @Author: 程前
 * @Date: 2025-01-03 14:15:28
 * @LastEditors: 程前
 * @LastEditTime: 2025-01-14 14:31:22
 */
interface Point {
    x: number;    // 经度
    y: number;    // 纬度
    z: number;    // 高度
}

interface ViewshedResult {
    points: Point[];
    isVisible: boolean[];
}

function findBreakPoints(startPoint: Point, terrainPoints: Point[]): {
    points: Point[];
    visibilityArray: boolean[];
} {
    const points: Point[] = [];
    const visibilityArray: boolean[] = [];
    
    let lastVisible = true;
    let maxAngle = -Infinity;

    // 确保至少有一个点
    points.push(terrainPoints[0]);
    visibilityArray.push(true);

    // 遍历所有地形点
    for (let i = 1; i < terrainPoints.length - 1; i++) {
        const point = terrainPoints[i];
        
        // 计算从观察点到当前点的距离
        const dx = point.x - startPoint.x;
        const dy = point.y - startPoint.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 计算视线角度
        const angle = Math.atan2(point.z - startPoint.z, distance);
        
        // 如果当前点的角度大于之前的最大角度，说明这个点遮挡了视线
        const isBlocked = angle > maxAngle;
        
        // 始终添加点，但更新可见性
        points.push(point);
        visibilityArray.push(!isBlocked);
        
        if (angle > maxAngle) {
            maxAngle = angle;
        }
    }

    // 确保添加最后一个点
    points.push(terrainPoints[terrainPoints.length - 1]);
    visibilityArray.push(visibilityArray[visibilityArray.length - 1]);

    return {
        points,
        visibilityArray
    };
}

self.onmessage = function(e) {
    const { center, terrainData, pointCount } = e.data;
    const results: ViewshedResult[] = [];

    for (let i = 0; i < pointCount; i++) {
        const terrainPoints = terrainData[i];
        const breakPoints = findBreakPoints(center, terrainPoints);

        results.push({
            points: breakPoints.points,
            isVisible: breakPoints.visibilityArray
        });

        if (i % 8 === 0) {
            self.postMessage({
                type: 'progress',
                progress: (i / pointCount) * 100
            });
        }
    }

    self.postMessage({
        type: 'complete',
        results: results
    });
};